import {defineStore} from 'pinia'
import {useStorage} from "@vueuse/core";
import {UserLoginResultType, UserLoginType} from "@/api/sys/admin/user/types";
import {handleError} from "@/utils/common-fn";
import {Ref} from "vue";
import {getUserInfo, loginApi} from "@/api/sys/admin/auth";

export const useUserStore = defineStore('user', () => {
    const accessToken = useStorage('accessToken', '')
    const roles: Ref<string[]> = ref([])
    const perms: Ref<string[]> = ref([])
    const id: Ref<number> = ref(-1)
    const nickname = ref("");
    const avatar = ref("");

    /**
     * 用户登录的一切处理
     */
    async function loginUser(data: UserLoginType) {
        const [err, result] = await handleError(() => loginApi(data))
        if (!err && result) {
            setToken(result)
            return true
        }
        return false
    }

    function setToken(tokens: UserLoginResultType) {
        const {tokenType= "Bearer ", accessToken: acToken} = tokens
        accessToken.value = tokenType + acToken
    }

    // 获取信息(用户昵称、头像、角色集合、权限集合)
    async function getInfo() {
        const userInfo = await getUserInfo()
        if (userInfo) {
            id.value = userInfo.id
            nickname.value = userInfo.nickname
            avatar.value = userInfo.avatar
            roles.value = userInfo.roles
            perms.value = userInfo.perms
        }
        return userInfo
    }


    // 重置
    function resetToken() {
        accessToken.value = "";
        nickname.value = "";
        avatar.value = "";
        roles.value = [];
        perms.value = [];
        id.value = -1
    }

    return {
        accessToken, roles, perms, id, nickname, avatar,
        loginUser, getInfo, resetToken
    }
})
